package com.lee.nio.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * NewIOClient
 * 零拷贝IO客户端
 *
 * @author dralee
 * @date 2022-01-01 15:03:18
 **/
public class NewIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 7001));

        String fileName = "C:/Users/dralee.LEEPC/Downloads/demo.zip";
        // 得到文件channel
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();
        // 准备发送
        long startTime = System.currentTimeMillis();
        // 在linux下一个transferTo方法就可以完成传输
        // 在windows下一次调用transferTo只能发送8M，就需要分段传输，而且需要注意传输时的位置
        // transferTo底层使用到零拷贝
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);// 只处文件只有4M没超过
        System.out.println("发送的总字节数=" + transferCount + " 耗时：" + (System.currentTimeMillis() - startTime));

        // 关闭
        socketChannel.finishConnect();
        fileChannel.close();
        // 发送的总字节数=4153088 耗时：9
    }
}
